/*
 * File:   ipc_controller.cpp
 * Author: dolphinigle
 *
 * Created on December 2, 2011, 4:13 PM
 */

#include "ipc_controller.h"
#include "ipc_manager.h"
#include "engine.h"
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/msg.h>

IPCController::IPCController(int to_receiver_msq_key,
                             int from_receiver_msq_key) {
  int msg_flag = 0666 | IPC_CREAT;

  to_receiver_msq_id_ = msgget(to_receiver_msq_key, msg_flag);
  if (to_receiver_msq_id_ < 0) {
    // Failed
    printf("msgget error\n");
    exit(4);
  }

  from_receiver_msq_id_ = msgget(from_receiver_msq_key, msg_flag);
  if (from_receiver_msq_id_ < 0) {
    // Failed
    printf("msgget error\n");
    exit(4);
  }

  manager_ = new IPCManager(to_receiver_msq_id_, from_receiver_msq_id_);
}

bool IPCController::IsExist(const string& path) {
  manager_->SendMessage("isexist");
  manager_->SendMessage(path);

  string ret = manager_->ReceiveMessage();
  return ret == "YES";
}

string IPCController::Ls(const string& path) {
  manager_->SendMessage("ls");
  manager_->SendMessage(path);

  string ret = manager_->ReceiveMessage();
  return ret;
}

string IPCController::Mkdir(const string& path) {
  manager_->SendMessage("mkdir");
  manager_->SendMessage(path);

  string ret = manager_->ReceiveMessage();
  return ret;
}

string IPCController::Rm(const string& path) {
  manager_->SendMessage("rm");
  manager_->SendMessage(path);

  string ret = manager_->ReceiveMessage();
  return ret;
}

string IPCController::Cp1(const string& path, const string& real_path) {
  manager_->SendMessage("cp1");
  manager_->SendMessage(path);
  manager_->SendMessage(real_path);

  string ret = manager_->ReceiveMessage();
  return ret;
}

string IPCController::Cp2(const string& real_path, const string& path) {
  manager_->SendMessage("cp2");
  manager_->SendMessage(real_path);
  manager_->SendMessage(path);

  string ret = manager_->ReceiveMessage();
  return ret;
}

string IPCController::Cat(const string& path) {
  manager_->SendMessage("cat");
  manager_->SendMessage(path);

  string ret = manager_->ReceiveMessage();
  return ret;
}

string IPCController::Close() {
  manager_->SendMessage("close");

  string ret = manager_->ReceiveMessage();
  return ret;
}

string IPCController::Status() {
  manager_->SendMessage("status");

  string ret = manager_->ReceiveMessage();
  return ret;
}

